/**splice() 方法通过移除或者替换已存在的元素和/或添加新元素就地改变一个数组的内容。
 *
 * @param {*} index
 * @param {*} count
 * @param  {...any} rest
 */
Array.prototype.mySplice = function (index, count, ...rest) {
  if (!Array.isArray(this)) throw new TypeError("musted be called by array");

  // 1. index 为undefiend，返回空数组，原数组不改变
  if (typeof index === "undefined") return [];
  // 2. index不为undefined,转成数字，转不了数字就取0
  index = Number(index) ? Number(index) : 0;
  // 3.如果index是负数，取正值
  if (index < 0) {
    index = Math.max(this.length + index, 0);
  }
  // 4.取正值后index还是大于数组长度，返回空数组
  if (index > this.length) return [];

  // 5. count,全部删除
  if (typeof count === "undefined") {
    count = this.length;
  }

  count = Number(count) ? Number(count) : 0;

  // 分三段取数组内容
  let startArr = this.slice(0, index);
  let deleteArr = this.slice(index, index + count);
  let endArr = this.slice(index + count);

  let res = [...startArr, ...rest, ...endArr];

  // 先置空再添加
  this.length = 0;
  for (let i = 0; i < res.length; i++) {
    this[i] = res[i];
  }

  return deleteArr;
};
// egg
let arr = [1, 2, 3, 4];
// console.log("[ arr ] >", arr.mySplice());
// console.log("[ arr ] >", arr.mySplice(100));
// console.log("[ arr ] >", arr.mySplice(0));
// console.log("[ arr ] >", arr.mySplice(0, 1));
console.log("[ arr ] >", arr.mySplice(0, 2, 7, 8));
console.log("[ arr ] >", arr);

let arr1 = [1, 2, 3, 4];
// console.log("[ arr1 ] >", arr1.splice());
// console.log("[ arr1 ] >", arr1.splice(100));
// console.log("[ arr1 ] >", arr1.splice(0, 1));
console.log("[ arr1 ] >", arr1.splice(0, 2, 7, 8));
console.log("[ arr1 ] >", arr1);
